from datetime import datetime
import random

def generate_formatted_receipt(store_name, items, discount=0.0, received=0.0):
    """
    生成指定格式的超市小票
    
    参数:
    store_name (str): 超市名称
    items (list): 购物商品列表，每个元素是元组 (商品名称, 单价, 数量)
    discount (float): 折扣金额，默认为0
    received (float): 实收金额
    """
    # 获取当前日期和时间
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 生成随机交易号
    transaction_id = random.randint(10000000, 99999999)
    
    # 计算商品总额
    total_amount = sum(price * quantity for _, price, quantity in items)
    total_quantity = sum(quantity for _, _, quantity in items)
    
    # 计算折后总额
    discounted_total = total_amount - discount
    if discounted_total < 0:
        discounted_total = 0
    
    # 计算找零
    change = received - discounted_total if received >= discounted_total else 0
    
    # 打印超市名称
    print(f"{store_name:^48}")
    print()
    
    # 第一个分隔区：单号和时间
    print("=" * 48)
    print(f"单号: {transaction_id}")
    print(f"时间: {current_time}")
   
    print()
    
    # 第二个分隔区：商品信息
    print("-" * 48)
    # 表头
    print(f"{'名称':<10}{'数量':>8}{'单价':>10}{'金额':>10}")
    # 商品列表
    for item in items:
        name, price, quantity = item
        amount = price * quantity
        # 截断过长的商品名称
        display_name = name[:5] + "..." if len(name) > 5 else name
        print(f"{display_name:<8}{quantity:>8}{price:>14.2f}{amount:>12.2f}")
    print("-" * 48)
    print()
    
    # 第三个分隔区：结算信息
    
    print(f"总数: {total_quantity}              总额: {total_amount:.2f}")
    print(f"折后总额: {discounted_total:.2f}")
    print(f"实收: {received:.2f}              找零: {change:.2f}")
    print(f"收银: 管理员")
    print("+" * 48)
    print()
    
    # 底部信息
    print("感谢您的光临，欢迎下次再来！".center(48))
    print("客服电话：400-123-4567".center(48))

if __name__ == "__main__":
    # 超市名称
    store = "惠民生活超市"
    
    # 模拟购物商品
    shopping_items = [
        ("全麦面包", 4.25, 1),
        ("原味薯片", 3.75, 2),
        ("可口可乐", 2.50, 4)
    ]
    
    # 生成并打印小票，设置折扣和实收金额
    generate_formatted_receipt(store, shopping_items, discount=5.0, received=100.0)
    